package com.xpp.yanbi.mq;

import com.rabbitmq.client.*;

public class TopicConsumer {

  private static final String EXCHANGE_NAME = "topic_exchange";

  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();

    Channel channel1 = connection.createChannel();
    String queueName1 = "backend_queue";
    channel1.queueDeclare(queueName1, true, false, false, null);
    channel1.queueBind(queueName1,EXCHANGE_NAME,"#.后端");

    Channel channel2 = connection.createChannel();
    String queueName2 = "frontend_queue";
    channel2.queueDeclare(queueName2,true,false,false,null);
    channel2.queueBind(queueName2,EXCHANGE_NAME,"#.前端");

    Channel channel3 = connection.createChannel();
    String queueName3 = "project_queue";
    channel3.queueDeclare(queueName3,true,false,false,null);
    channel3.queueBind(queueName2,EXCHANGE_NAME,"#.项目");

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    DeliverCallback deliverCallback1 = (consumerTag, delivery) -> {
        String message = new String(delivery.getBody(), "UTF-8");
        System.out.println(" [backend] Received '" +
            delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
    };
    DeliverCallback deliverCallback2 = (consumerTag, delivery) -> {
      String message = new String(delivery.getBody(), "UTF-8");
      System.out.println(" [frontend] Received '" +
              delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
    };
    DeliverCallback deliverCallback3 = (consumerTag, delivery) -> {
      String message = new String(delivery.getBody(), "UTF-8");
      System.out.println(" [project] Received '" +
              delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
    };
    channel1.basicConsume(queueName1, true, deliverCallback1, consumerTag -> { });
    channel2.basicConsume(queueName2, true, deliverCallback2, consumerTag -> { });
    channel3.basicConsume(queueName3, true, deliverCallback3, consumerTag -> { });
  }
}